package io.sundial.coordination.curator;

import com.google.common.base.Preconditions;
import io.sundial.coordination.node.Node;
import io.sundial.coordination.tree.Tree;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Curator 节点树
 *
 * @author Payne 646742615@qq.com
 * 2018/12/24 12:13
 */
public class CachedTree implements Tree {
    private final String root;
    private final TreeCache cache;

    CachedTree(String root, TreeCache cache) {
        Preconditions.checkNotNull(root, "root must not be null");
        Preconditions.checkNotNull(cache, "data must not be null");
        this.root = root;
        this.cache = cache;
    }

    @Override
    public String getRoot() {
        return root;
    }

    @Override
    public Map<String, Node> getChildren(String path) {
        Map<String, ChildData> map = cache.getCurrentChildren(path);
        if (map == null) {
            return null;
        }
        Map<String, Node> children = new LinkedHashMap<>(map.size());
        for (Map.Entry<String, ChildData> entry : map.entrySet()) {
            String key = entry.getKey();
            ChildData value = entry.getValue();
            Node child = new Child(key, value);
            children.put(key, child);
        }
        return children;
    }

    @Override
    public Node getChild(String path) {
        return null;
    }

    static class Child implements Node {
        private final String path;
        private final ChildData data;

        Child(String path, ChildData data) {
            Preconditions.checkNotNull(path, "path must not be null");
            Preconditions.checkNotNull(data, "data must not be null");
            this.path = path;
            this.data = data;
        }

        @Override
        public String getPath() {
            return path;
        }

        @Override
        public byte[] getData() {
            return data != null ? data.getData() : null;
        }

        @Override
        public int getVersion() {
            return data != null ? data.getStat().getVersion() : -1;
        }
    }
}
